import { ICaptcha, IUpdateInfo, IUpdatePassword, IUserInfoVo, IUserLogin } from './login.typings'
import { http } from '@/utils/http'
import { useAuthHeaders } from '@/utils/token'

const API_BASE_URL = import.meta.env.VITE_API_BASE_URL

/**
 * 登录表单
 */
export interface ILoginForm {
  userInfo: IUserInfo
  iv: string
  encryptedData: string
  code: string
}

export interface IUserInfo {
  nickname: string
  avatarUrl: string
  gender: string
  province: string
  city: string
  country: string
  email: string
}

/**
 * 用户登录
 * @param loginForm 登录表单
 */
export const login = (loginForm: ILoginForm) => {
  return http.post<IUserLogin>('/user/login', loginForm)
}

/**
 * 获取用户信息
 */
export const getUserInfo = () => {
  return http.get<IUserInfoVo>('/user/info')
}

/**
 * 退出登录
 */
export const logout = () => {
  return http.get<void>('/user/logout')
}

/**
 * 修改用户密码
 */
export const updateUserPassword = (data: IUpdatePassword) => {
  return http.post('/user/updatePassword', data)
}

/**
 * 获取微信登录凭证
 * @returns Promise 包含微信登录凭证(code)
 */
export const getWxCode = () => {
  return new Promise<UniApp.LoginRes>((resolve, reject) => {
    uni.login({
      provider: 'weixin',
      success: (res) => resolve(res),
      fail: (err) => reject(new Error(err)),
    })
  })
}

export const getUserProfile = () => {
  return new Promise<UniApp.GetUserInfoRes>((resolve, reject) => {
    uni.getUserProfile({
      desc: '获取信息用于展示',
      lang: 'zh_CN',
      success: resolve,
      fail: reject,
    })
  })
}

/**
 * 微信登录参数
 */

/**
 * 微信登录
 * @param params 微信登录参数，包含code
 * @returns Promise 包含登录结果
 */
export const wxLogin = (data: ILoginForm) => {
  return http.post<IUserLogin>(API_BASE_URL + '/api/v1/user/login', data)
}
